/*
*   @Author: 1296
*   @Date: 2025-05-05
*   @Description: 课程管理
*/
<template>
  <div class="course-container">
    <div class="course-header">
      <h2>我的课程</h2>
      <el-button type="primary" @click="showAddCourseDialog = true">新增课程</el-button>
    </div>

    <div class="course-cards">
      <el-row :gutter="20">
        <el-col :span="6" v-for="course in courseList" :key="course.id">
          <el-card
              class="course-card"
              shadow="hover"
              @click="handleLeftClick(course)"
              @contextmenu.prevent="handleRightClick(course, $event)"
          >
            <div class="course-card-image">
              <img :src="course.avatar || defaultAvatar" class="course-image" alt="CourseImage"/>
            </div>
            <div class="course-card-info">
              <h3 class="course-name">{{ course.name }}</h3>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="pagination-container">
      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="totalCourses"
          layout="prev, pager, next"
          @current-change="handlePageChange"
      ></el-pagination>
    </div>

    <!-- 课程详情对话框 -->
    <el-dialog
        v-model="showCourseDetails"
        width="60%"
        append-to-body
    >
      <template #header>
        <h2>{{ editMode ? '修改课程' : '课程详情' }}</h2>
      </template>
      <div class="course-details-container">
        <div v-if="!editMode" class="avatar-container">
          <h4>课程头像</h4>
          <img :src="selectedCourse.avatar || defaultAvatar" class="course-avatar-large" alt="CurrentAvatar"/>
        </div>
        <el-row v-else :gutter="20">
          <el-col :span="12">
            <div class="avatar-container">
              <h4>当前头像</h4>
              <img :src="selectedCourse.avatar || defaultAvatar" class="course-avatar-large" alt="CurrentAvatar"/>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="avatar-container">
              <h4>新头像</h4>
              <div v-if="newAvatarPreview">
                <img :src="newAvatarPreview" class="course-avatar-large" alt="NewAvatar"/>
              </div>
              <div v-else class="new-avatar-upload">
                <el-upload
                    class="avatar-uploader"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                    :http-request="handleAvatarUpload"
                >
                  <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </div>
            </div>
          </el-col>
        </el-row>
        </div>
        <div class="course-details-info">
          <el-descriptions :column="1">
            <el-descriptions-item label="课程ID">{{ selectedCourse.id }}</el-descriptions-item>
            <el-descriptions-item label="课程名称">
              <span v-if="!editMode">{{ selectedCourse.name }}</span>
              <el-input v-else v-model="editForm.name" placeholder="请输入课程名称" />
            </el-descriptions-item>
          </el-descriptions>
        </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="!editMode" @click="enterEditMode">修改</el-button>
          <el-button v-else @click="cancelEdit">取消</el-button>
          <el-button v-if="editMode" type="primary" @click="updateCourse">保存</el-button>
          <el-button type="danger" @click="showConfirmDeleteDialog">删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增课程对话框 -->
    <el-dialog
        v-model="showAddCourseDialog"
        width="40%"
        title="新增课程"
        @close="resetAddCourseForm"
    >
      <el-form
          ref="addCourseForm"
          :model="addCourseForm"
          :rules="addCourseRules"
          label-width="100px"
      >
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="addCourseForm.name" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="课程头像">
          <el-upload class="add-course-avatar-uploader"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="handleAddCourseAvatarUpload"
          >
          <img v-if="addCourseForm.avatar" :src="addCourseForm.avatar" class="add-course-avatar" alt="courseAvatar"/>
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
    <span class="dialog-footer">
      <el-button @click="showAddCourseDialog = false">取消</el-button>
      <el-button type="primary" @click="addCourse">确定</el-button>
    </span>
      </template>
    </el-dialog>
  </div>

  <confirm-modal
      :show="showConfirmDelete"
      :message="'此操作将永久删除课程 \'' + selectedCourse?.name + '\', 是否继续?'"
      :confirmText="'确定'"
      :cancelText="'取消'"
      @confirm="confirmDeleteCourse"
      @close="cancelDeleteCourse"
      @update:show="updateConfirmDeleteShow"
  />
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import ConfirmModal from "@/components/ConfirmModal.vue";
import store from "@/store";

const api = axios.create({
  baseURL: store.getters.getBaseURL
});

// 添加请求和响应拦截器
api.interceptors.request.use(config => {
  const token = sessionStorage.getItem('userToken');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

api.interceptors.response.use(
    response => response,
    error => {
      if (error.response?.status === 401) {
        window.location.href = '/loginAndRegister';
      }
      return Promise.reject(error);
    }
);

export default {
  components: {
    ConfirmModal,
    Plus
  },
  data() {
    return {
      courseList: [],
      currentPage: 1,
      pageSize: 8,
      totalCourses: 0,
      showCourseDetails: false,
      selectedCourse: null,
      defaultAvatar: require('@/assets/example.png'),
      showAddCourseDialog: false,
      addCourseForm: {
        name: '',
        avatar: ''
      },
      addCourseRules: {
        name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' }
        ]
      },
      editMode: false,
      editForm: {
        name: '',
        avatar: null
      },
      newAvatarPreview: null,
      showConfirmDelete: false
    };
  },
  created() {
    this.getCourseList();
  },
  methods: {
    // 获取课程列表
    getCourseList() {
      api
          .get(`/course/list?pageNo=${this.currentPage}&pageSize=${this.pageSize}`)
          .then(response => {
            if (response.data.status === 'success') {
              this.courseList = response.data.data.list;
              this.totalCourses = response.data.data.resultCount;
              if (this.totalCourses === undefined) {
                this.totalCourses = this.courseList.length;
              }
            } else {
              ElMessage.error(response.data.info || '获取课程列表失败');
            }
          })
          .catch(error => {
            console.error('Error fetching course list:', error);
            ElMessage.error('获取课程列表失败');
          });
    },
    // 处理左键点击事件
    handleLeftClick(course) {
      const jobCode = sessionStorage.getItem('jobCode');
      const encodedName = encodeURIComponent(course.name);
      this.$router.push(`/${jobCode}/course/${course.id}?name=${encodedName}`);
    },
    handleRightClick(course, event) {
      event.preventDefault();
      this.selectedCourse = course;
      this.showCourseDetails = true;
      this.editMode = false;
    },
    // 处理分页变化
    handlePageChange(page) {
      this.currentPage = page;
      this.getCourseList();
    },
    // 打开新增课程对话框
    openAddCourseDialog() {
      this.showAddCourseDialog = true;
    },
    // 重置新增课程表单
    resetAddCourseForm() {
      this.addCourseForm = {
        name: '',
        avatar: ''
      };
      this.$refs.addCourseForm?.resetFields();
    },
    // 新增课程
    addCourse() {
      this.$refs.addCourseForm.validate((valid) => {
        if (valid) {
          api.post('/course/add', this.addCourseForm)
              .then(response => {
                if (response.data.status === 'success') {
                  ElMessage.success('课程添加成功');
                  this.showAddCourseDialog = false;
                  this.getCourseList();
                } else {
                  ElMessage.error(response.data.info || '添加课程失败');
                }
              })
              .catch(error => {
                console.error('Error adding course:', error);
                ElMessage.error('添加课程失败');
              });
        }
      });
    },
    // 进入编辑模式
    enterEditMode() {
      this.editMode = true;
      this.editForm = {
        name: this.selectedCourse.name,
        avatar: null
      };
      this.newAvatarPreview = null;
    },
    // 退出编辑模式并重置表单
    exitEditMode() {
      this.editMode = false;
      this.editForm = {
        name: '',
        avatar: null
      };
      this.newAvatarPreview = null;
    },

    // 更新课程
    updateCourse() {
      const courseId = this.selectedCourse.id;
      const formData = {};

      // 只添加有变化的字段
      if (this.editForm.name !== this.selectedCourse.name) {
        formData.name = this.editForm.name;
      }

      if (this.editForm.avatar) {
        formData.avatar = this.editForm.avatar;
      }

      if (Object.keys(formData).length === 0) {
        ElMessage.warning('没有检测到任何修改');
        this.exitEditMode();
        return;
      }

      api.put(`/course/${courseId}`, formData)
          .then(response => {
            if (response.data.status === 'success') {
              ElMessage.success('课程更新成功');
              // 只有在成功后才更新本地数据
              if (this.editForm.name) {
                this.selectedCourse.name = this.editForm.name;
              }
              if (this.editForm.avatar) {
                this.selectedCourse.avatar = this.editForm.avatar;
              }
              this.exitEditMode();
              this.getCourseList();
            } else {
              ElMessage.error(response.data.info || '更新课程失败');
            }
          })
          .catch(error => {
            console.error('Error updating course:', error);
            ElMessage.error('更新课程失败');
          });
    },
    // 取消修改
    cancelEdit() {
      this.exitEditMode();
    },
    // 头像上传前检查
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        ElMessage.error('上传头像图片只能是图片格式!');
      }
      if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },
    // 处理头像上传预览
    handleAvatarUpload({ file }) {
      if (!this.beforeAvatarUpload(file)) {
        return;
      }

      const reader = new FileReader();
      reader.onload = (e) => {
        this.newAvatarPreview = e.target.result;
        this.editForm.avatar = e.target.result;
      };
      reader.readAsDataURL(file);
    },
    handleAddCourseAvatarUpload({ file }) {
      const reader = new FileReader();
      reader.onload = (e) => {
        this.addCourseForm.avatar = e.target.result;
      };
      reader.readAsDataURL(file);
    },
    // 显示确认删除的对话框
    showConfirmDeleteDialog() {
      if (!this.selectedCourse) {
        ElMessage.error('未选择要删除的课程');
        return;
      }
      this.showConfirmDelete = true;
    },

    // 确认删除课程
    confirmDeleteCourse() {
      api.delete(`/course/${this.selectedCourse.id}`)
          .then(response => {
            if (response.data.status === 'success') {
              ElMessage.success('课程删除成功');
              this.showCourseDetails = false;
              this.showConfirmDelete = false;
              this.getCourseList();
            } else {
              ElMessage.error(response.data.info || '删除课程失败');
            }
          })
          .catch(error => {
            console.error('Error deleting course:', error);
            ElMessage.error('删除课程失败');
          });
    },

    // 取消删除课程
    cancelDeleteCourse() {
      this.showConfirmDelete = false;
    },

    // 更新自定义确认弹窗的显示状态
    updateConfirmDeleteShow(show) {
      this.showConfirmDelete = show;
    }
  }
};
</script>

<style scoped>
.course-container {
  padding: 20px;
}

.course-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

h2 {
  margin-bottom: 10px;
  color: #333;
}

.course-cards {
  margin-bottom: 30px;
}

.course-card {
  height: 100%;
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 12px;
  overflow: hidden;
}

.course-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.course-card-image {
  height: 160px;
  width: 100%;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.course-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.course-avatar-large {
  width: 150px;
  height: 150px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 20px;
}

.course-card-info {
  padding: 15px;
}

.course-name {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.pagination-container {
  text-align: center;
  margin-top: 20px;
}

.course-details-container {
  display: flex;
  gap: 40px;
  align-items: flex-start;
  justify-content: center;
}

.course-details-avatar {
  flex: 0 0 300px;
  display: flex;
  justify-content: center;
}

.course-details-info {
  flex: 1;
  padding: 0 20px;
}

.el-descriptions {
  border: none;
}

.el-descriptions-item__content {
  color: #666;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar-uploader {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 178px;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-container {
  text-align: center;
  margin-bottom: 30px;
  width: 100%;
}

.avatar-container h4 {
  margin-bottom: 15px;
  color: #666;
  font-weight: 500;
}

.course-avatar-large {
  width: 150px;
  height: 150px;
  object-fit: cover;
  border-radius: 8px;
  margin: 0 auto 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.new-avatar-upload {
  width: 150px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 10px auto;
}

.new-avatar-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-placeholder {
  width: 150px;
  height: 150px;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  transition: var(--el-transition-duration-fast);
  background-color: #fafafa;
}

.avatar-placeholder:hover {
  border-color: var(--el-color-primary);
}

.add-course-avatar-uploader {
  width: 178px;
  height: 178px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: var(--el-transition-duration-fast);
}

.add-course-avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.add-course-avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>